import io
import os
import random
import string
import subprocess
import time

from flask_restful import Resource, reqparse
from flask import send_file, jsonify

# 参数解析
parser = reqparse.RequestParser()
parser.add_argument('mermaid_code', type=str, required=True, help='mermaid_code is required.')


# 读取doc格式的文件
class generate_image(Resource):
    def get(self):
        args = parser.parse_args()
        mermaid_code: str = args.get('mermaid_code')
        mermaid_code = mermaid_code.replace(r'\n', os.linesep)

        # 创建临时文件保存Mermaid代码
        temp_file_path = f'{str(time.time()) + "".join(random.choice(string.ascii_letters + string.digits) for _ in range(10))}.mmd'
        with open(temp_file_path, 'w') as temp_file:
            temp_file.write(mermaid_code)

        # 获取当前文件的绝对路径
        current_file_path = os.path.abspath(__file__)

        # 获取当前文件的父级目录
        parent_directory = os.path.dirname(current_file_path)

        # 获取父级目录的父级目录
        grandparent_directory = os.path.dirname(parent_directory)

        # 获取父级目录的父级目录的绝对路径
        absolute_grandparent_directory = os.path.abspath(os.path.dirname(grandparent_directory))

        # 生成一个包含指定长度随机字符的字符串
        random_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10)) + str(
            int(time.time()))
        # print(f"{absolute_grandparent_directory}/static/{random_string}.png")

        # 调用mmdc命令生成图片
        output_file = f"{absolute_grandparent_directory}/static/{random_string}.png"


        try:
            # 将Mermaid代码通过stdin传递给mmdc命令
            result = subprocess.run(['mmdc', '-i', temp_file_path, '-o', output_file, '-w', '7200', '-H', '7200'])
            if result.returncode == 0:
                pass
            else:
                # 删除临时文件
                os.remove(temp_file_path)
                raise Exception("执行命令出错")
        except Exception as e:
            return jsonify({'error': 'Failed to generate image'})

        # 删除临时文件
        os.remove(temp_file_path)
        return {
            "url": f"http://8.219.60.106:10002/static/{random_string}.png"
        }

